package com.sfh.cp.user.pst;

import com.sfh.cp.user.ReqRegister;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.RxBusEventManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import crm.sfh.server.Const;
import crm.sfh.server.SUser;
import crm.sfh.server.entity.EUser;

/**
 * 功能描述:
 *
 * @date 2018/5/1
 */
public class PstRegister extends AbstractPresenter<IPstRegister.IVRegister> implements IPstRegister {



    @Override
    public void register(final ReqRegister req) {
        getView().showLoading(true);
        BmobQuery<SUser> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("phone",req.getPhone());
        bmobQuery.findObjects(AppCacheManager.getApplication(), new FindListener<SUser>() {
            @Override
            public void onSuccess(List<SUser> list) {

                if (list != null && !list.isEmpty()){
                    getView().hideLoading();
                    getView().showToast("用户已存在");
                    return;
                }

               final SUser user = new SUser();
                user.setPassword(req.getPassword());
                user.setPhone(req.getPhone());
                user.setCharm (0L);
                user.setWealth (0L);
                user.setName (req.getPhone());
                user.save(AppCacheManager.getApplication(), new SaveListener() {
                    @Override
                    public void onSuccess() {
                        getView().hideLoading();
                        EUser eUser = user.getUser();
                        RxBusEventManager.postEvent(eUser);
                        AppCacheManager.newInstance().putCache(true, Const.USER,user);
                        getView().onSuccess();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        getView().hideLoading();
                        getView().showToast(s);
                    }
                });
            }

            @Override
            public void onError(int i, String s) {
                getView().hideLoading();
                getView().showToast(s);
            }
        });
    }
}
